package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.mapper.UserMapper;
import com.bwie.utils.R;
import com.bwie.vo.loginForm;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
* @author 24026
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-09-09 09:43:29
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public R sendCodePhone(loginForm loginForm) {

        String code = RandomUtil.randomNumbers(4);
        if(loginForm.getPhone() == null){
            return R.ERROR(500,"请先输入手机号");
        }
        System.out.println("验证码"+code);
        redisTemplate.opsForValue().set(loginForm.getPhone(),code,5, TimeUnit.MINUTES);
        return R.OK(code);
    }

    @Override
    public R loginPhone(loginForm loginForm) {
        String code = redisTemplate.opsForValue().get(loginForm.getPhone());
        if(code == null){
            return R.ERROR(500,"验证码已过期");
        }
        if(!loginForm.getCode().equals(code)){
            return R.ERROR(500,"验证码错误");
        }

        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUserPhone, loginForm.getPhone()));
        if(user == null){
            return R.ERROR(500,"手机号未注册");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", user.getUserId()).compact();

        String key = "token-"+user.getUserId();

        redisTemplate.opsForValue().set(key,token,5, TimeUnit.MINUTES);
        user.setToken(token);
        return R.OK(user);
    }
}




